var manageQuota=[];
$(function(){
    showCondition(true, 1, 1, 1, []);
    var totalCaseCnt;
    var barColor = ["#f07043","#50a1d4","#7bd9a5","#d0648a","#f58db2","#f2b3c9"];

    //全院总体指标
    var totalQuota = [
        ['InCaseCnt', '入组病例数'],
        ['CMI', 'CMI值'],
        ['AvgDays', '平均住院日'],
        ['AvgFee', '次均费用'],
        ['AvgDrugFee', '次均药品费用(元)'],
        ['AvgMateFee', '次均耗材费用(元)'],
        ['DrugRatio', '药品费用占比(%)'],
        ['MaterialRatio', '耗材费用占比(%)']
    ];

    //消耗指数指标
    var effQuota = [
        ['TimeEff', '时间消耗指数'],
        ['FeeEff', '费用消耗指数'],
        ['MedFeeEff', '医疗费用消耗指数'],
        ['TechFeeEff', '医技费用消耗指数'],
        ['NursFeeEff', '护理费用消耗指数'],
        ['DrugMaterFeeEff', '药品耗材费用消耗指数'],
        ['ManageFeeEff', '管理费用消耗指数']
    ];

    //五大类费用指标
    var feeQuota = [
        ['MedFee', '医疗类费用'],
        ['TechFee', '医技类费用'],
        ['NursFee', '护理类费用'],
        ['DrugMaterFee', '药品耗材类费用'],
        ['ManageFee', '管理类费用']
    ];


    //科室监测指标(标杆比)
    var deptQuota = [
        ['AvgFee', '次均费用'],
        ['AvgDrugFee', '次均药品费用'],
        ['DrugRatio', '药品费用占比(%)'],
        ['AvgMateFee', '次均耗材费用'],
        ['MaterialRatio', '耗材费用占比(%)'],
        ['MedFee','次均医疗类费用'],
        ['MedFeeRatio','医疗类费用占比(%)'],
        ['TechFee','次均医技类费用'],
        ['TechFeeRatio','医技类费用占比(%)'],
        ['NursFee','次均护理类费用'],
        ['NursFeeRatio','护理类费用占比(%)'],
        ['DrugMaterFee','次均药耗类费用'],
        ['DrugMateRatio','药耗类费用占比(%)'],
        ['ManageFee','次均管理类费用'],
        ['ManageFeeRatio','管理类费用占比(%)'],
        ['AvgDays','平均住院日']
    ];

    //科室监测指标(绩效比)
    var manageDeptQuota = [
        ['AvgFee', '次均费用'],
        ['AvgDrugFee', '次均药品费'],
        ['DrugRatio', '药品费用占比(%)'],
        ['AvgMateFee', '次均耗材费用'],
        ['MaterialRatio', '耗材费用占比(%)'],
        ['AvgDays','平均住院日']
    ];


    var param = jQuery.extend(true,{},paramTabPage[tabId]);
    var dateTo=param.dateTo;   	 //截止日期
    var pType=param.pType; 	//人员类型 0是全体 1是医保

    $.post(contextPath + "/feeAnalysisDep/getManagerQuotaCode.dhc", {"dateTo":dateTo,"pType":pType}).done(function(data) {
        if(data.success){
            if(data.data.length>0){
                var data=data.data;
                for(var o in  data){
                    var code= data[o].PARQUOTA_CODE;
                    for(var i in manageDeptQuota){
                        if(manageDeptQuota[i][0]==code){
                            manageQuota.push(manageDeptQuota[i]);
                            break;
                        }
                    }
                }
            }
        }
    });


    //构造科室监测指标checkbox
    $('#deptQuota').html('');
    $('#deptQuota').append('<label class="input-label"><input type="checkbox" id="deptQuotaSelectAll">全部</label>');
    for (var i = 0; i < deptQuota.length; i++) {
        var q = deptQuota[i];
        $('#deptQuota').append('<label class="input-label">' +
            '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
            '</label>');
    }
    // for (var q of deptQuota) {
    //     $('#deptQuota').append('<label class="input-label">' +
    //         '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
    //     '</label>');
    // }

    //监测对象改变时的点击事件
    $('input[name="compareType"]:radio').on('ifChecked', function(event){ //ifCreated 事件应该在插件初始化之前绑定
        var compareType = $('input[name="compareType"]:checked').val();
        $('#deptQuota').html('');
        $('#deptQuota').append('<label class="input-label"><input type="checkbox" id="deptQuotaSelectAll">全部</label>');
        if(compareType=="manage"){
            for (var i = 0; i < manageQuota.length; i++) {
                var q = manageQuota[i];
                $('#deptQuota').append('<label class="input-label">' +
                    '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
                    '</label>');
            }
            // for (var q of manageQuota) {
            //     $('#deptQuota').append('<label class="input-label">' +
            //         '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
            //     '</label>');
            // }
        }else{
            for (var i = 0; i < deptQuota.length; i++) {
                var q = deptQuota[i];
                $('#deptQuota').append('<label class="input-label">' +
                    '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
                    '</label>');
            }
            // for (var q of deptQuota) {
            //     $('#deptQuota').append('<label class="input-label">' +
            //         '<input type="checkbox" value="'+q[0]+'" name="deptQuota" data-name="'+ q[1] +'">' + q[1] +
            //     '</label>');
            // }
        }
        //初始化iCheck
        $('#deptQuota input').iCheck({
            checkboxClass: 'icheckbox_minimal-blue',
            radioClass: 'iradio_minimal-blue'
        });
        //全选事件
        $('#deptQuotaSelectAll').off('ifChecked').off('ifUnchecked');
        $('#deptQuotaSelectAll').on('ifChecked', function(event){
            $('#deptQuota input').iCheck('check');
        }).on('ifUnchecked', function(event){
            $('#deptQuota input').iCheck('uncheck');
        });

    });


    //全选事件
    $('#deptQuotaSelectAll').off('ifChecked').off('ifUnchecked');
    $('#deptQuotaSelectAll').on('ifChecked', function(event){
        $('#deptQuota input').iCheck('check');
    }).on('ifUnchecked', function(event){
        $('#deptQuota input').iCheck('uncheck');
    });

    //超标科室查询单击事件
    $('#queryDeptFeeBtn').click(queryDeptFee);
    //获取指标值
    function getQuotaValue(quotaCode, monitorType, callback, compareType){
        var param=drgUI.setAjaxData(tabId);
        param.monitorType=monitorType;
        if (compareType){
            param.compareType = compareType;
        }
        param.quotaCode=quotaCode;
        if(compareType == "std") {
            param.msCode = "std_computer" ;
        }else if(compareType == "manage"){
            param.msCode = "manager_inner" ;
        }
        param.isGetCc = "1";

        $.post(contextPath + "/DrgsIndexCal/indexCal.dhc", param).done(function(data) {
            if(data.success){
                if(data.data.length>0){
                    data = data.data;
                    callback(data);
                }
            }
        });
    }

    //获取全院整体情况
    var quotaCodes = totalQuota.map(function(v){return v[0]}).join(',')+','
        + effQuota.map(function(v){return v[0]}).join(',')+','
        + feeQuota.map(function(v){return v[0]}).join(',')
        + ',TotalFee,TotalCaseCnt';
    getQuotaValue(quotaCodes, 'hosp', function(result){
        result = result[0];
        totalCaseCnt = result.TotalCaseCnt;
        var totalQuotaHtml = '';
        for (var i = 0; i < totalQuota.length; i++) {
            var q = totalQuota[i];
            totalQuotaHtml += '<td><p class="value">'+formatNumber(result[q[0]],2)+'</p><p class="title">'+q[1]+'</p></td>';
        }
        // for (var q of totalQuota) {
        //     totalQuotaHtml += '<td><p class="value">'+formatNumber(result[q[0]],2)+'</p><p class="title">'+q[1]+'</p></td>';
        // }
        $('#'+tabId+' #hospTable tr').html(totalQuotaHtml);

        //消耗指数监测
        var effOption = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['指数值']
            },
            color: barColor,
            xAxis: {
                type: 'category',
                data: effQuota.map(function(v){return v[1]})
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: '指数值',
                data: effQuota.map(function(v){return result[v[0]]}),
                type: 'bar'
            }]
        };
        var effChart = echarts.init(document.getElementById('effChart'));
        effChart.setOption(effOption);

        //费用构成对比图
        var feeOption = {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:['本期值','标杆值']
            },
            color: barColor,
            xAxis: {
                type: 'category',
                data: feeQuota.map(function(v){return v[1]})
            },
            yAxis: {
                name: '费用占比（%）',
                type: 'value'
            },
            series: [{
                name: '本期值',
                data: feeQuota.map(function(v){return feeRatio(result, v[0])}),
                type: 'bar',
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            },{
                name: '标杆值',
                data: feeQuota.map(function(v){return feeRatio(result, v[0], 'cc')}),
                type: 'bar',
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            }]
        };
        var feeChart = echarts.init(document.getElementById('feeChart'));
        feeChart.setOption(feeOption);

        queryDeptFee();
    });

    //查询科室次均费用、费用构成及其对比情况表
    function queryDeptFee(){
        //科室监测指标表格填充固定列
        var deptQuotaFixed = [
            ['AvgFee', '次均费用'],
            ['AvgDays','平均住院日'],
            ['AvgDrugFee', '次均药品费用(元)'],
            ['DrugRatio', '药品费用占比(%)'],
            ['AvgMateFee', '次均耗材费用(元)'],
            ['MaterialRatio', '耗材费用占比(%)'],
            ['MedFee','次均医疗类费用(元)'],
            ['NursFee','次均护理类费用(元)'],
            ['ManageFee','次均管理类费用(元)'],
            ['TechFee','次均医技类费用(元)'],
            ['DrugMaterFee','次均药耗类费用(元)']
        ];

        var selectedQuota; //表格固定
        //选择的拼接项
        var selectedQuotaNew = $('input[name="deptQuota"]:checked').map(function(i,v){return [[$(v).val(),$(v).data('name')]]}).toArray();

        selectedQuota =deptQuotaFixed.concat(selectedQuotaNew);
        var compareType = $('input[name="compareType"]:checked').val();
        var quotaCode = selectedQuota.map(function(v){return v[0]}).join(',');
        quotaCode +=',TotalCaseCnt,FeeEff';
        var columns=[
            {"data": "depname","title":'科室名称',
                "render": function(obj, type, full) {
                    return '<a href="javascript:loadDepPage(\''+full.ccode+'\',\''+full.ddesc+'\')">'+full.ddesc+'</a>';
                }
            },
            {"data": "TotalCaseCnt","title":'病例数',
                "render": function(obj, type, full) {
                    return formatNumber(full.TotalCaseCnt,0);
                }
            },
            {"data": "case_ratio","title":'病例数全院占比(%)',
                "render": function(obj, type, full) {
                    return formatNumber(full.TotalCaseCnt*100/totalCaseCnt,2);
                }
            },
            {"data": "FeeEff","title":'费用消耗指数',
                "render": function(obj, type, full) {
                	return '<span>'+formatNumber(full.FeeEff,2)+'</span>';
                   /* if (full.FeeEff > full['FeeEffcc']){
                    	var str='[超标]标杆值:'+formatNumber(full['FeeEffcc'],2);
                        return '<span class="text-danger" title="'+str+'">'+formatNumber(full.FeeEff,2)+'</span>';
                    } else {
                    	var str='[未超标]标杆值:'+formatNumber(full['FeeEffcc'],2);
                        return '<span title="'+str+'">'+formatNumber(full.FeeEff,2)+'</span>';
                    }*/
                }
            }
        ];

        //根据页面选择的指标，动态拼接表头
        for (var i = 0; i < deptQuotaFixed.length; i++) {
            var q = deptQuotaFixed[i];
            //for (var q of deptQuotaFixed) {
            (function(q){
                columns.push({"data": q[0],"title":q[1],
                    "render": function(obj, type, full) {
                        //五大类费用的次均费用需要除以病例数(但目前五大类费用的标杆值找不到)
                        if(q[0]=="MedFee"||q[0]=="TechFee"||q[0]=="NursFee"||q[0]=="DrugMaterFee"||q[0]=="ManageFee"){
                            if (full[q[0]] > full[q[0]+'cc']){
                            	var str='[超标]标杆值:'+(full[q[0]+'cc']/full.TotalCaseCnt).toFixed(2);
                                return '<span class="text-danger" title="'+str+'">'+(full[q[0]]/full.TotalCaseCnt).toFixed(2)+'</span>';
                            } else {
                            	var str='[未超标]标杆值:'+(full[q[0]+'cc']/full.TotalCaseCnt).toFixed(2);
                                return '<span title="'+str+'">'+(full[q[0]]/full.TotalCaseCnt).toFixed(2)+'</span>';
                            }
                        }else{
                            if (full[q[0]] > full[q[0]+'cc']){
                            	var str='[超标]标杆值:'+formatNumber(full[q[0]+'cc'],2);
                                return '<span class="text-danger" title="'+str+'">'+formatNumber(full[q[0]],2)+'</span>';
                            } else {
                            	var str='[未超标]标杆值:'+formatNumber(full[q[0]+'cc'],2);
                                return '<span title="'+str+'">'+formatNumber(full[q[0]],2)+'</span>';
                            }
                        }
                    }
                });
            }(q));
        }
        var paramsDataTables={
            searching:true,
            lengthChange:true,
            ordering:true,
            info:false,
            scrollX:true,
            scrollY:'285px',
            orderCellsTop:true,
            order: [[3, 'desc']]
        };

        getQuotaValue(quotaCode, 'dep', function (data) {

            var finalData=[]; //超标的科室指标数据
            var allOverCount = 0;
            if(selectedQuotaNew==null||selectedQuotaNew==""||selectedQuotaNew==undefined){
                finalData=data; //第一次进来及不点查询按钮默认全部科室展示
            }else{
                data.forEach(function(deptdata){
                    var isAllOver = false;
                    for (var i = 0; i <selectedQuotaNew.length ; i++) {
                        var q = selectedQuotaNew[i];
                        //for (var q of selectedQuotaNew) {
                        //如果指标没有标杆值，则都不超标
                        if(deptdata[q[0]+'cc']==null||deptdata[q[0]+'cc']==""||deptdata[q[0]+'cc']==undefined){
                            isAllOver = false;
                            break;
                        }else{
                            if(deptdata[q[0]] > deptdata[q[0]+'cc']){
                                isAllOver = true;
                                continue;
                            } else {
                                isAllOver = false;
                                break;
                            }
                        }
                    }
                    if (isAllOver) {
                        finalData=finalData.concat(deptdata);
                        allOverCount++;
                    }
                });
            }

            var overDeptOption = {
                title: {
                    text: '指标均超标科室数',
                    left: 'center',
                    bottom: 0
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{b}: {c} ({d}%)"
                },
                series: [
                    {
                        type:'pie',
                        radius: ['50%', '70%'],
                        avoidLabelOverlap:false,
                        label: {
                            normal: {
                                show : true,
                                position : 'center',
                                formatter : allOverCount+"/"+data.length,
                                textStyle: {
                                    fontSize: 20,
                                    baseline : 'bottom'
                                }
                            }
                        },
                        data:[
                            {value:allOverCount, name:'均超标'},
                            {value:data.length-allOverCount, name:'未超标'}
                        ]
                    }
                ]
            };
            var deptPieChart = echarts.init(document.getElementById('deptPieChart'));
            deptPieChart.setOption(overDeptOption);

            $('#deptFeeTableDiv').html('<table id="deptFeeTable" class="table display nowrap" style="width: 100%;"></table>');
            $("#deptFeeTable").dataTableBasic(columns,finalData,paramsDataTables);

        }, compareType);

    }

    //费用占比格式化
    function feeRatio(data, quotaCode, cc){
        cc = cc || '';
        return (data[quotaCode]/100/data['TotalFee'+cc]).toFixed(0);
    }

    //初始化iCheck
    $('input').iCheck({
        checkboxClass: 'icheckbox_minimal-blue',
        radioClass: 'iradio_minimal-blue'
    });
});

/**
 *
 * @ Discription：跳转科室
 */
function loadDepPage(code,desc){
    var param = jQuery.extend(true,{},paramTabPage[tabId]);
    param.pardepCode = code;
    param.depDesc = desc;
    param.monitorType='dep';
    var destUrl = '/pages/yizheng/fenxi/feeAnalysisByDep.jsp';//目标页面的url
    var destPageTitle = desc + '|费用分类分析';//目标页面的title
    var destPageId = code + 'depFeeAnalysis';//目标页面的ID
    openTab(destUrl, destPageTitle,destPageId,destPageId,param);
}
